import { getUserInfoApi, userLoginApi } from "@/api/base/login";
import { joinParentPath } from "@/routers/utils/menuHelper";
import { store } from "@/redux";
import { setAccessToken, setRefreshToken, setUserInfo } from "../user/action";
import { cloneDeep } from "lodash-es";
import { setBackMenuList } from "./action";
import { setLanguage, setTabsList } from "../global/action";
import { HOME_URL } from "@/config/config";

/** 登录 */
export const LoginAction = async (params: any): Promise<any> => {
	try {
		const { accessToken, refreshToken } = await userLoginApi(params);
		// save token
		store.dispatch(setAccessToken(accessToken));
		store.dispatch(setRefreshToken(refreshToken));
		return afterLoginAction();
	} catch (error) {
		return Promise.reject(error);
	}
};

export const afterLoginAction = async () => {
	const userInfo = await getUserInfoAction();
	const menus = cloneDeep(userInfo.menus);
	joinParentPath(menus);
	// set menu
	store.dispatch(setBackMenuList(menus));
	return userInfo;
};

export const getUserInfoAction = async () => {
	const userInfo = await getUserInfoApi();
	// set userInfo
	store.dispatch(setUserInfo(userInfo));
	return userInfo;
};

/** 退出登录 */

export const logoutAction = async () => {
	store.dispatch(setAccessToken(undefined));
	store.dispatch(setUserInfo(null));
	store.dispatch(setBackMenuList([]));
};

/** 刷新菜单 */
export const refreshMenuAction = async () => {
	await afterLoginAction();
	store.dispatch(setTabsList([{ title: "Home Page", path: HOME_URL }]));
};

/** 切换语言 */

export const changeLanguageAction = async (lang: string) => {
	// set language
	store.dispatch(setLanguage(lang));
	// refresh menu
	await afterLoginAction();
	// 重载界面 解决 form中label国际化无法刷新问题
	setTimeout(() => window.location.reload(), 10);
};
